package com.itheima.mp.domain.dto;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhangbaiyan
 * @date 2024-09-11 19:04
 * @description:
 * @version:
 */
@Data
@ApiModel(description = "分页结果")
public class PageDTO<U> {
    @ApiModelProperty("总条数")
    private Long total;
    @ApiModelProperty("总页数")
    private Long Pages;
    @ApiModelProperty("集合")
    private List<?> list;


    public  static<PO,VO> PageDTO<VO> of(Page<PO> p,Class<VO> clazz){
        PageDTO<VO> dto=new PageDTO<>();
        //3.1 总条数
        dto.setTotal(p.getTotal());
        //3.2总页数
        dto.setPages(p.getPages());
        //3.3 当前页数据
        List<PO> records=p.getRecords();
        if (CollUtil.isEmpty(records)){
            dto.setList(Collections.emptyList());
            return dto;
        }
        //3.4 拷贝user的VO

        dto.setList(BeanUtil.copyToList(records, clazz));

        //返回
        return dto;
    }



    public  static<PO,VO> PageDTO<VO> of(Page<PO> p, Function<PO, VO> convertor){
        PageDTO<VO> dto=new PageDTO<>();
        //3.1 总条数
        dto.setTotal(p.getTotal());
        //3.2总页数
        dto.setPages(p.getPages());
        //3.3 当前页数据
        List<PO> records=p.getRecords();
        if (CollUtil.isEmpty(records)){
            dto.setList(Collections.emptyList());
            return dto;
        }
        //3.4 拷贝user的VO

        dto.setList(records.stream().map(convertor).collect(Collectors.toList()));

        //返回
        return dto;
    }
}
